﻿var ns = namespace("kaskelot.sp.ui");

ns.toolbox = function () {
    function init() {
        kaskelot.sp.ui.toolbox.reloadItems(window.location.hash, function () {
            $("#toolbox")
                .chosen({ allow_single_deselect: false, disable_search: true })
                .change(function () {
                    var v = $(this).val();
                    $(this).val(0).trigger("liszt:updated");
                    eval(v);
                }
            );
        });
	}

	function reloadItems(tabId, callback) {
		var list = $("#toolbox");
		var toolboxId = list.data("pageurl") + tabId;

		$.ajax({
			url: L_Menu_BaseUrl + "/_vti_bin/Kaskelot.SP.Resources/ClientNavigationService.svc/GetToolboxItems",
			type: "GET",
			data: { toolboxConfigId: toolboxId },
			processData: true,
			success:
				function (data) {
					if (!data.GetToolboxItemsResult.HasError) {
						list.empty();
						list.append("<option value='0'></option>");
						list.append(
							$("#menuitem-template").render(data.GetToolboxItemsResult.Data)
						);

						list.removeAttr('disabled');
						list.trigger("liszt:updated");

						checkVisibility();

						if (callback)
						    callback();
					}
				},
			error:
				function (xhr) {
					kaskelot.sp.ui.prompts.showErrorPrompt(xhr.responseText);
				}
		});
	}

	function checkVisibility() {
		var list = $("#toolbox");

		if (list.html() == "" || $.trim(list.html()) == "<option value=\"0\"></option>") {
			$("#toolbox-container").hide();
		} else {
			$("#toolbox-container").show();
		}
	}

	return {
		init: init,
		reloadItems: reloadItems,
		checkVisibility: checkVisibility
	};
}();